package algorithm.leetcode;

import java.util.Arrays;

/**
 * @program: util
 * @description: 三数之和为0，最接近的三数之和
 * @author: zhouliangliang
 * @create: 2021-04-06 15:33
 **/
public class TNTZ {

    public void execute(int []array) {
        //sort
        Arrays.sort(array);

        Arrays.stream(array).forEach(item->{
            System.out.print(item + ",");
        });
        System.out.println();

        for(int i=0; i<array.length-2; i++) {
            if(array[i] > 0) {
                break;
            }

            int j = i+1;
            int index = array.length-1;
            while (j < index) {
                if(array[i] + array[j] + array[index] < 0 || array[j]==array[j+1]) {
                    j++;
                    continue;
                }

                if(array[i] + array[j] + array[index] > 0 || array[index]==array[index-1]) {
                    index--;
                    continue;
                }

                if(array[i] + array[j] + array[index] == 0){
                    System.out.println(array[i] + " + " + array[j] + " + " + array[index] + " = 0 i= " + i + " j= " + j + " index= " + index);
                    j++;
                    index--;
                }
            }
        }
    }

    public static void main(String[] args) {
        int []array = new int[]{-8,0,8,-2,-3,-5,4,6,5,-9,7,2};
        new TNTZ().execute(array);
    }
}
